import React, { useEffect, useRef, useState } from 'react';
import PageTitle from '@/components/PageTitle';
import { Button, Form, Input, message, Select, DatePicker, Modal } from 'antd';
import Tables from '@/hoc/Tables';
import Models from '@/components/Models';
import { Orignizers } from './index.d';
import styles from './index.less';
import { FAIR_LIST } from '@/services/list';
import moment from 'moment';
import { delExhibition, insertExhibition, updateExhibition } from '@/services/fair';
import { BasicLayoutProps } from '@/layouts/BasicLayout';
import { TableProps } from '@/global.d';
import { queryAllUser } from '@/services/user';
const { Option } = Select;
const { RangePicker } = DatePicker;

let type: {
  [as: number]: any;
} = {
  1: {
    color: '#F65401',
    text: '网络展',
  },
  2: {
    color: '#333',
    text: '线下展',
  },
};

let exhibitionStatus: {
  [as: number]: any;
} = {
  1: {
    color: '#F65401',
    text: '征集作品中',
  },
  2: {
    color: '#F65401',
    text: '展览中',
  },
  3: {
    color: '#333',
    text: '已关闭',
  },
  4: {
    color: '#333',
    text: '未发布',
  },
};

const Regime: React.FC<BasicLayoutProps> = props => {
  const childRef = useRef<TableProps | any>();
  let title = props?.route?.name;
  let columns: any[] = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
    },
    {
      title: '展览名称',
      dataIndex: 'exhibitionName',
      key: 'exhibitionName',
      ellipsis: false,
      align: 'left',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (_: any, text: any) => <span style={{ color: type[text.type]?.color }}>{type[text.type].text}</span>,
    },
    {
      title: '时间',
      dataIndex: 'startLaunchTime',
      key: 'startLaunchTime',
      render: (_: string, text: Orignizers) => (
        <span>
          {text?.startLaunchTime}至{text?.endLaunchTime}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'exhibitionStatus',
      key: 'exhibitionStatus',
      render: (_: any, text: any) => <span style={{ color: exhibitionStatus[text.exhibitionStatus]?.color }}>{exhibitionStatus[text.exhibitionStatus].text}</span>,
    },
    {
      title: '操作',
      width: 250,
      render: (item: any) => (
        <div className="operation">
          <span
            onClick={() => {
              onEdit(item, 1);
            }}>
            查看
          </span>
          <span
            onClick={() => {
              onEdit(item, 0);
            }}>
            修改
          </span>
          <span
            onClick={() => {
              onisDis(item);
            }}>
            删除
          </span>
        </div>
      ),
    },
  ];
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(false);
  const [issee, setIssee] = useState<boolean>(false);
  const [itemObj, setItemObj] = useState<any>({});
  const [userList, setUserList] = useState<any[]>([]);

  /**
   * 添加展览
   */
  const onChange = () => {
    setVisible(true);
  };

  /**
   * 弹窗关闭
   */
  const handleCancel = () => {
    setVisible(false);
    setItemObj({});
    form.resetFields();
    setIssee(false);
  };

  /**
   * 提交
   * @param values
   */
  const onFinish = (values: Orignizers) => {
    let value: Orignizers = {
      ...values,
      startLaunchTime: moment(values?.startLaunchTime1?.[0]).format('YYYY-MM-DD'),
      endLaunchTime: moment(values?.startLaunchTime1?.[1]).format('YYYY-MM-DD'),
      id: itemObj?.id,
      userIds: values?.user?.join(','),
    };
    delete value.startLaunchTime1;
    delete value.user;

    if (!itemObj?.id) {
      insertExhibition(value).then((res: any) => {
        if (res?.responseCode == 200) {
          message.success('保存成功');
          handleCancel();
          childRef.current.setQuery({});
        } else {
          message.success('保存失败');
        }
      });
    } else {
      updateExhibition(value).then((res: any) => {
        if (res?.responseCode == 200) {
          message.success('编辑成功');
          handleCancel();
          childRef.current.setQuery({});
        } else {
          message.success('编辑失败');
        }
      });
    }
  };

  /**
   * 编辑
   * @param item
   */
  const onEdit = (item: Orignizers, id: number) => {
    setItemObj(item);
    form.setFieldsValue({
      ...item,
      startLaunchTime1: [moment(item?.startLaunchTime) ?? undefined, moment(item?.endLaunchTime) ?? undefined],
      user: item?.userIds?.split(','),
    });
    if (id) {
      setIssee(true);
    }
    onChange();
  };

  /**
   * 获取用户列表
   */
  useEffect(() => {
    queryAllUser({}).then(res => {
      if (res?.responseCode == '200') {
        setUserList(res?.data);
      }
    });
  }, []);

  /**
   * 删除
   */
  const onisDis = (item: Orignizers) => {
    Modal.confirm({
      title: '删除提示',
      content: '确定要删除此条展览信息吗？',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        delExhibition({ id: item.id }).then((res: any) => {
          if (res?.responseCode == 200) {
            message.success('删除成功');
            childRef.current.setQuery({});
          } else {
            message.success('删除失败');
          }
        });
      },
    });
  };

  return (
    <div className={styles.regimePage}>
      <PageTitle
        title={title}
        right={
          <Button className="btn_red" onClick={onChange}>
            添加
          </Button>
        }
      />
      <div className="regime_table">
        <Tables childRef={childRef} url={FAIR_LIST} columns={columns} />
      </div>
      <Models className="add_regime" width="540px" visible={visible} handleCancel={handleCancel}>
        <Form labelAlign="left" {...layout} form={form} name="control-hooks" onFinish={onFinish}>
          <div className="add_user">{issee ? '查看·展览活动' : itemObj?.id ? '修改·展览活动' : '新增·展览活动'}</div>
          <div className="add_user_form">
            <Form.Item label="展览名称" name="exhibitionName" required={false} rules={[{ required: true, message: '请输入展览名称' }]}>
              <Input disabled={issee} size="large" className="regime_inputs" allowClear placeholder="请输入展览名称" />
            </Form.Item>
            <Form.Item label="类型" name="type" required={false} rules={[{ required: true, message: '请选择类型' }]}>
              <Select disabled={issee} size="large" className="regime_input" placeholder="请选择类型" allowClear>
                <Option value={1}>网络展览</Option>
                <Option value={2}>线下展览</Option>
              </Select>
            </Form.Item>
            <Form.Item label="展馆" name="exhibitionHall" required={false} rules={[{ required: true, message: '请输入展馆名称' }]}>
              <Input disabled={issee} size="large" className="regime_inputs" allowClear placeholder="请输入展馆名称" />
            </Form.Item>
            <Form.Item label="举办方" name="organizers" required={false} rules={[{ required: true, message: '请输入举办方名称' }]}>
              <Input disabled={issee} size="large" className="regime_inputs" allowClear placeholder="请输入举办方名称" />
            </Form.Item>

            <Form.Item label="开展时间" name="startLaunchTime1" required={false} rules={[{ required: true, message: '请选择开展时间' }]}>
              <RangePicker disabled={issee} size="large" className="regime_inputs" format="YYYY-MM-DD" />
            </Form.Item>

            <Form.Item label="展览状态" name="exhibitionStatus" required={false} rules={[{ required: true, message: '请选择展览状态' }]}>
              <Select disabled={issee} size="large" className="regime_input" placeholder="请选择展览状态" allowClear>
                <Option value={1}>征集作品中</Option>
                <Option value={2}>展览中</Option>
                <Option value={3}>已闭关</Option>
                <Option value={4}>未发布</Option>
              </Select>
            </Form.Item>

            <Form.Item label="用户权限" name="user" required={false} rules={[{ required: true, message: '请选择用户权限' }]}>
              <Select disabled={issee} mode="tags" size="large" className="regime_inputs" placeholder="请选择用户权限" allowClear>
                {userList.map(el => (
                  <Option key={el.id + '123123123_id_key'} value={`${el.id}`}>
                    {el?.userName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </div>
          {issee ? (
            <div className="regime_btns">
              <Button className="btn_cold" onClick={handleCancel}>
                关闭
              </Button>
            </div>
          ) : (
            <div className="regime_btns">
              <Button className="btn_cold" onClick={handleCancel}>
                取消
              </Button>
              <Button className="btn_red" htmlType="submit">
                提交
              </Button>
            </div>
          )}
        </Form>
      </Models>
    </div>
  );
};

export default Regime;
